var express = require('express');
var QuestModel = require('../db/questModel')
var AnswerModel = require('../db/answerModel')
var InfoModel = require('../db/infoModel')

module.exports = async function (req, res) {
    var openCode = req.params.opencode
    var reqBody = req.body
    let ipArr = req.ip.split(":");
    let ip = ipArr[ipArr.length - 1]
    let time = Date.now()
    answer = []
    for (let i = 0; i < reqBody.answer.length; i++) {
        var element = reqBody.answer[i]
        answer.push(element)
    }
    //查找questid
    var questid = await QuestModel.findOne({openCode: openCode}, {_id: 0, id: 1})
    if (questid === null) {
        res.status(400).send({
            status: 400,
            msg: "提交失败"
        })
    }

    //查找answerid
    var answerid = await InfoModel.findOne({key: "answerid"}, {_id: 0, value: 1})
    if (answerid === null) {
        res.status(400).send({
            status: 400,
            msg: "提交失败"
        })
    }

    //更新answerid
    InfoModel.updateOne({key: "answerid"}, {$set: {value: answerid._doc["value"] + 1}}, function (error, info) {
    })

    //存储answer
    new AnswerModel({
        id: answerid._doc["value"],
        questId: questid._doc["id"],
        answers: answer,
        pin:1,
        ip:ip,
        answerTime:time
    }).save(function (error, answer) {
        if (error === null) {
            res.send({
                status: 200,
                msg: "提交成功"
            })
        } else {
            res.status(400).send({
                status: 400,
                msg: "提交失败"
            })
        }
    })
}